package com.blt.govdata.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.blt.govdata.controller.base.BaseController;
import com.blt.govdata.core.constants.Constants;
import com.blt.govdata.model.TSysRoleMenu;
import com.blt.govdata.service.ITSysMenuService;
import com.blt.govdata.service.ITSysRoleMenuService;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色配置菜单前端控制器
 * </p>
 * @author AustinGJ123
 * @since 2018-03-26
 */
@RestController
@RequestMapping("/tSysRoleMenu")
//todo 将所有的XXX修改为真实值
public class TSysRoleMenuController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ITSysRoleMenuService service;
    @Autowired
    private ITSysMenuService menuService;

    /**
     * 给角色配置菜单
     */
    @RequestMapping(value = "confRoleMenu")
    public Map<String, Object> confRoleMenu(TSysRoleMenu sysRoleMenu) {
        boolean result = this.service.insert(sysRoleMenu);
        logger.info("给角色配置菜单");
        return ImmutableMap.of("status", "true", "data", result);
    }


    /**
     * 给角色配置菜单（批量插入:角色ID一个,菜单ID多个并用逗号分隔）
     */
    @RequestMapping(value = "confRoleMenuBatch", params = "rId")
    public Map<String, Object> confRoleMenuBatch(Integer rId, String mId) {
        this.service.delete(BeanUtils.instantiate(EntityWrapper.class).where("r_id = {0}", rId));
        if (StringUtils.isBlank(mId)) return ImmutableMap.of("status", "true", "data", true);
        List<String> mIds = Arrays.asList(mId.split(","));
        List<Map<String, Integer>> fIdList = this.menuService.selectMaps(BeanUtils.instantiate(EntityWrapper.class)
                .setSqlSelect("pid")
                .where("is_delete = {0}", Constants.UN_DELETED)
                .in("id", mIds)
                .groupBy("pid"));
        List<Integer> fIds = fIdList.stream().map(e->e.get("pid")).collect(Collectors.toList());
        mIds.stream().forEach(e -> {
            TSysRoleMenu menu = BeanUtils.instantiate(TSysRoleMenu.class);
            menu.setrId(rId);
            menu.setmId(Integer.valueOf(e));
            this.service.insert(menu);
        });
        fIds.stream().forEach(e -> {
            TSysRoleMenu menu = BeanUtils.instantiate(TSysRoleMenu.class);
            menu.setrId(rId);
            menu.setmId(e);
            this.service.insert(menu);
        });
        logger.info("给角色配置菜单");
        return ImmutableMap.of("status", "true", "data", true);
    }



}
